package ae.pcfc.etks.online.web.controller.user.general.company;

/* $Id: UserCompanyController 
 * Copyright (C) 2011, Trakhees
 *  
 *  History
 *
 * Date  			Author 					Remarks
 * -------------------------------------------------------------
 * April 12, 2011 	Neha_Chauhan 	        Created
 *
 */

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.util.WebUtils;

import ae.pcfc.etks.online.common.delegate.ClientRegistrationDelegate;
import ae.pcfc.etks.online.common.delegate.SecretQuestionDelegate;
import ae.pcfc.etks.online.common.delegate.UserDelegate;
import ae.pcfc.etks.online.common.vo.ClientCompanyVO;
import ae.pcfc.etks.online.common.vo.LabelVO;
import ae.pcfc.etks.online.common.vo.NonClientCompanyVO;
import ae.pcfc.etks.online.common.vo.SCCompanyVO;
import ae.pcfc.etks.online.common.vo.SecretQuestionVO;
import ae.pcfc.etks.online.common.vo.UserVO;
import ae.pcfc.etks.online.web.ConstantsAdmin;
import ae.pcfc.etks.online.web.ViewPath;
import ae.pcfc.etks.online.web.ViewUtils;
import ae.pcfc.etks.online.web.controller.BaseController;
import ae.pcfc.etks.online.web.model.ClientCompanyRegistration;
import ae.pcfc.etks.online.web.model.UserModel;
import ae.pcfc.etks.online.web.util.SecurityUtils;

/**
 * Controller that handles all {@link UserCompanyController}-related requests,
 * i.e.: all requests for /user/general/company/*
 * 
 * @author Neha Chauhan
 */

@Controller
@RequestMapping(ViewPath.USER_COMPANY)
public class UserCompanyController extends BaseController {

	private UserDelegate userDelegate;
	private ClientRegistrationDelegate clientRegistrationDelegate;

	@Resource(name = "clientRegistrationDelegate")
	public void setClientRegistrationDelegate(
			ClientRegistrationDelegate clientRegistrationDelegate) {
		this.clientRegistrationDelegate = clientRegistrationDelegate;
	}

	@Resource(name = "userDelegate")
	public void setUserDelegate(UserDelegate userDelegate) {
		this.userDelegate = userDelegate;
	}

	private SecretQuestionDelegate secretQuestionDelegate;

	@Resource(name = "secretQuestionDelegate")
	public void setSecretQuestionDelegate(
			SecretQuestionDelegate secretQuestionDelegate) {
		this.secretQuestionDelegate = secretQuestionDelegate;
	}

	@ModelAttribute(value = ConstantsAdmin.USER_COMPANY_REGISTRATION_INFM_REQUEST_MODEL_KEY)
	public NonClientCompanyVO populateUserInfoEdit(HttpServletRequest request,
			@RequestParam(value = "id", required = false) String id) {

		// TODO Here we'll place the logic to load the User Data through an Id
		return new NonClientCompanyVO();

	}

	@ModelAttribute(ConstantsAdmin.USER_SECRETQUESTION_REQUEST_MODEL_KEY)
	public List<LabelVO> populateSecretQuestionList() {

		List<LabelVO> labelList = new ArrayList<LabelVO>();

		LabelVO labelVO;
		List<SecretQuestionVO> secretQuestionVOs = secretQuestionDelegate
				.getSecretQuestionList();

		for (SecretQuestionVO secretQuestionVO : secretQuestionVOs) {
			labelVO = getMapper().map(secretQuestionVO, LabelVO.class);
			labelList.add(labelVO);

		}
		return labelList;
	}

	/**
	 * Custom handler for displaying the form, i.e.: GET requests for
	 * /user/general/company/
	 * 
	 * @see WEB-INF/jsp/user/general/company/edit.jsp
	 */

	@RequestMapping(value = "/edit.htm", method = RequestMethod.GET)
	public void form(
			@RequestParam(value = "clientId", required = true) String id,
			@ModelAttribute(value = ConstantsAdmin.USER_COMPANY_EDIT_INFO_REQUEST_MODEL_KEY) UserModel command) {

	}

	@ModelAttribute(ConstantsAdmin.USER_COMPANY_EDIT_INFO_REQUEST_MODEL_KEY)
	public UserModel populateUserInfo(HttpServletRequest request,
			@RequestParam(value = "id", required = false) String id) {

		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		String strUserName = null;

		if (principal instanceof UserDetails) {
			strUserName = ((UserDetails) principal).getUsername();
		} else {
			strUserName = principal.toString();
		}

		ClientCompanyVO clientCompanyVO = this.clientRegistrationDelegate
				.findClientCompanyByUserName(strUserName);

		if (clientCompanyVO != null) {

			UserModel clientCompanyRegister = new UserModel();
			UserVO userVO = null;

			// if (clientCompanyVO.getUserVOs() != null
			// && clientCompanyVO.getUserVOs().size() > 0)
			// userVO = clientCompanyVO.getUserVOs().get(0);

			userVO = this.userDelegate.findUserByUserName(strUserName);
			if (userVO != null) {
				getMapper().map(userVO, clientCompanyRegister);
				return clientCompanyRegister;
			}
		}
		return new UserModel();
	}

	@ModelAttribute(value = ConstantsAdmin.CLIENT_COMPANY_REGISTER_SUMMARY_REQUEST_MODEL_KEY)
	public SCCompanyVO populateReferenceData(HttpServletRequest request,
			@RequestParam(value = "clientId", required = false) String clientId) {

		String trakheesId = SecurityUtils.decrypt(clientId);

		SCCompanyVO scCompanyVO = clientRegistrationDelegate
				.findSCCompanyByTrakheesId(trakheesId);

		if (scCompanyVO == null)
			scCompanyVO = new SCCompanyVO();

		return scCompanyVO;

	}

	/**
	 * Custom handler for displaying the form, i.e.:POST requests for
	 * /user/general/company/edit.jsp
	 * 
	 * @see #form(ClientCompanyRegistration)
	 * @see WEB-INF/jsp/user/general/company/edit.jsp
	 */

	@RequestMapping(method = RequestMethod.POST, value = "/edit.htm")
	public String form(
			HttpServletRequest request,
			SessionStatus status,
			@ModelAttribute(value = ConstantsAdmin.USER_COMPANY_EDIT_INFO_REQUEST_MODEL_KEY) @Valid UserModel userCompanyEditInfo,
			BindingResult errors) {

		boolean isSave = WebUtils.hasSubmitParameter(request,
				ConstantsAdmin.SAVE_BUTTON);

		if (isSave) {
			if (errors.hasErrors()) {

				return ViewUtils.DEFAULT_VIEW;

			} else {

				ClientCompanyVO companyClientVO = new ClientCompanyVO();

				if (companyClientVO != null) {
					getMapper().map(userCompanyEditInfo, companyClientVO);

					UserVO userVO = new UserVO();

					getMapper().map(userCompanyEditInfo, userVO);
					userVO.setStrPassword(SecurityUtils
							.hashPassword(userCompanyEditInfo
									.getStrPassword()));

					if (userVO.getStrEmailNotification() == null
							|| userVO.getStrEmailNotification().equals(""))
						userVO.setStrEmailNotification("N");
					if (userVO.getStrSmsNotification() == null
							|| userVO.getStrSmsNotification().equals(""))
						userVO.setStrSmsNotification("N");
					this.clientRegistrationDelegate.updateClientCompany(userVO);

					// String[] messageArgs = new String[] {
					// messageSource.getMessage("success.user.info.edit", null,
					// RequestContextUtils.getLocale(request)) };
					request.setAttribute(ConstantsAdmin.SUCCESS_PARAM,
							getMessageSource().getMessage("success.user.info.edit",
									null,
									RequestContextUtils.getLocale(request)));
				}
			}

		}
		return ViewUtils.DEFAULT_VIEW;
	}

}
